package gui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import core.Environment;
import core.Square;
import core.Square.Type;

public class GridPanel extends JPanel {

	private static final long serialVersionUID = 1L;
	private JLabel[][] labelMatrix;
	public static ImageIcon flowerIcon, wallIcon, tileIcon, ciccioIcon, smokingIcon, tableIcon, mealIcon, doorIcon;
	public int labelSize;
	static Environment env;

	static Square.Type currType;
	static ImageIcon currIcon;

	public GridPanel(Environment env) {
		GridPanel.env = env;
		init();
		update();
	}

	void init() {

		setLayout(new FlowLayout());

		JPanel flowPanel = new JPanel();
		add(flowPanel);
		flowPanel.setLayout(new GridLayout(8, 8));

		ciccioIcon = ImageLoader.ciccioIcon;
		flowerIcon = ImageLoader.flowerIcon;
		tileIcon = ImageLoader.tileIcon;
		mealIcon = ImageLoader.mealIcon;
		smokingIcon = ImageLoader.smokingIcon;
		tableIcon = ImageLoader.tableIcon;
		wallIcon = ImageLoader.wallIcon;
		doorIcon = ImageLoader.doorIcon;

		labelMatrix = new JLabel[8][8];

		currType = Type.clean;
		currIcon = tileIcon;

		for (int i = 0; i < 8; i++)
			for (int j = 0; j < 8; j++) {
				GridBagConstraints constraints = new GridBagConstraints();
				constraints.fill = GridBagConstraints.BOTH;
				constraints.gridx = i;
				constraints.gridy = j;
				final JLabel label = new JLabel();
				label.setPreferredSize(new Dimension(ImageLoader.iconSize,
						ImageLoader.iconSize));
				label.addMouseListener(new ClickHandler(label, i, j));
				labelMatrix[i][j] = label;
				flowPanel.add(label, constraints);
			}
	}

	public void update() {
		for (int i = 0; i < 8; i++)
			for (int j = 0; j < 8; j++) {
				if (i % 2 == 0) {
					if (env.floor.get(i / 2, j) == Square.Type.flowers)
						labelMatrix[i][j].setIcon(flowerIcon);
					if(env.floor.get(i / 2, j) == Square.Type.meal)
						labelMatrix[i][j].setIcon(mealIcon);
					if(env.floor.get(i / 2, j) == Square.Type.smoking)
						labelMatrix[i][j].setIcon(smokingIcon);
					if(env.floor.get(i / 2, j) == Square.Type.table)
						labelMatrix[i][j].setIcon(tableIcon);
					if (env.floor.get(i / 2, j) == Square.Type.clean)
						labelMatrix[i][j].setIcon(tileIcon);
					if (env.agent.x == i / 2 && env.agent.y == j)
						labelMatrix[i][j].setIcon(ciccioIcon);
				} else {
					if (env.floor.isDoor(i / 2 - 1 / 2, j))
						labelMatrix[i][j].setIcon(doorIcon);
					else
						labelMatrix[i][j].setIcon(wallIcon);
				}
			}
		try {
			Thread.sleep(250);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}